package org.example.demo4.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.demo4.model.CaptchaProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private static Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Autowired
    private CaptchaProperties cp;


    //一分钟
    private static long VALID_TIME_OUT = 60 * 1000;

    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        //生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(cp.getWidth(), cp.getHeight());

        //打印验证码
        String code = lineCaptcha.getCode();
        System.out.println("System生成验证码：" + code);
        logger.info("Logger生成验证码：" + code);

        //存储session
        session.setAttribute(cp.getSession().getKey(),code);
        session.setAttribute(cp.getSession().getData(), new Date());
        System.out.println(lineCaptcha.getCode());

        //把验证码写到浏览器
        try {
            lineCaptcha.write(response.getOutputStream());
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Pragma","No-cache");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @RequestMapping("/check")
    public Boolean check(String captcha,HttpSession session) {
        System.out.println("用户输入验证码：" + captcha);
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }

        String code = (String) session.getAttribute(cp.getSession().getKey());
        Date date = (Date) session.getAttribute(cp.getSession().getData());

        if (date == null || (System.currentTimeMillis()-date.getTime())> VALID_TIME_OUT) {
            return false;
        }
        return captcha.equalsIgnoreCase(code);
    }
}
